package com.qc.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.qc.dao.BusinessFollowDao;
import com.qc.entity.BusinessFollow;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Repository("businessFollowDao")
public class BusinessFollowDaoImpl implements BusinessFollowDao{

	@Resource(name="jdbcTemplate")
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public int saveBusinessFollow(BusinessFollow businessFollow) {
		
		String sql = "insert into t_business_follow(shop_id,user_id)values(?,?)";
		
		return jdbcTemplate.update(sql,new Object[]{businessFollow.getShopId(),businessFollow.getUserId()});
	}

	@Override
	public void deleteBusinessFollow(long shopId,long userId) {
		
		String sql = "delete from t_business_follow where shop_id = " +shopId + " and user_id =" +userId;
        
		jdbcTemplate.update(sql);
	}

	@Override
	public int getUserFollowId(long userId, long shopId) {
		
		String sql = "select count(*) from t_business_follow where shop_id = "+shopId + " and user_id =" +userId;
		
		return jdbcTemplate.queryForInt(sql);
	}

	@Override
	public List<BusinessFollow> listAllBusinessFollow(long userId, int pageNo, int pageSize) {
		
		int beginRow = (pageNo - 1)* pageSize;
		
		String sql = "select a.*,"
				+ "	b.shop_name,"
				+ "	b.follow_number,"
				+ "	b.province,"
				+ " b.city,"
				+ " b.region,"
				+ "(SELECT COUNT(*) FROM t_coupon WHERE shop_id = a.shop_id and overdue_state = 2 and coupon_type = 2 and shelves_state = 1) overdue_state,"
				+ " d.image,"
				+ " d.title"
				+ " from t_business_follow a "
				+ " left join t_merchant b on b.shop_id = a.shop_id "
				+ " left join t_business_inform d on d.shop_id = b.shop_id "
				+ " where 1 = 1 ";
		
			if (userId != 0) {
				sql += " and a.user_id ="+userId+" ";
			}
		
			sql += " order by a.modified_time DESC ";
			sql += " LIMIT "+ String.valueOf(beginRow)+ "," + pageSize;
			
			return jdbcTemplate.query(sql, new BeanPropertyRowMapper(BusinessFollow.class));
			
	}

}
